<template>
  <div class="app-container">
    <div v-show="showIndexList">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="客户名称" prop="customerId">
           <el-select v-model="queryParams.customerId" filterable clearable  placeholder="请选择客户信息">
              <el-option
                  v-for="dict in searchCustomerList"
                  :key="dict.customerId"
                  :label="dict.customerName"
                  :value="dict.customerId"
                  />
          </el-select>
        </el-form-item>
        <el-form-item label="付款方式" prop="paymentType">
          <el-select v-model="queryParams.paymentType" placeholder="请选择付款方式" clearable size="small">
            <el-option
                  v-for="dict in paymentTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            :loading="exportLoading"
            @click="handleExport"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="customerList">
        <el-table-column label="客户名称" align="center" :show-overflow-tooltip="true" fixed width="200">
          <template slot-scope="scope">
            <router-link :to="{ path:'/contract',query:{customerId:scope.row.customerId}}" class="link-type">
              <span>{{ scope.row.customerName }}</span>
            </router-link>
          </template>
        </el-table-column>

        <el-table-column label="付款方式" align="center" prop="paymentType" :formatter="paymentTypeFormat" min-width="300" v-if="columns[0].visible"/>
        <el-table-column label="合同金额" align="center" prop="contractSum" v-if="columns[1].visible" :formatter="numberFormat" />
        <el-table-column label="已开票金额" align="center" prop="invoiceSum" v-if="columns[2].visible" :formatter="numberFormat"/>
        <el-table-column label="未开票金额" align="center" prop="noInvoiceSum" v-if="columns[3].visible" :formatter="numberFormat"/>
        <el-table-column label="已开票比例%" align="center" prop="invoiceProportion" v-if="columns[4].visible"/>
        <el-table-column label="已收货款" align="center" prop="collectionSum" v-if="columns[5].visible" :formatter="numberFormat"/>
        <el-table-column label="已收款比例%" align="center" prop="collectionProportion" v-if="columns[6].visible"/>
        <el-table-column label="应收/预收款" align="center" prop="receivables" v-if="columns[7].visible" :formatter="numberFormat"/>
        <el-table-column label="所欠货款" align="center" prop="debt" v-if="columns[8].visible" :formatter="numberFormat"/>

        <el-table-column fixed="right" align="center" label="操作" width="190" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-paperclip"
              @click="handleAddContract(scope.row)"
            >添加合同</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <ContractEditDialog :show.sync="open" :edit-config="contractEditConfig"></ContractEditDialog>
    </div>
    <CustomerEdit v-if="!showIndexList" @onEditBack="editBack" :editConfig="editConfig"></CustomerEdit>
  </div>
</template>

<script>
import CustomerEdit from './edit'
import ContractEditDialog from '../contract/editDialog'
import { listCustomer, listCustomerDetail, getCustomer, delCustomer, exportCustomer } from "@/api/business/customer";

export default {
  name: "Customer",
  components:{
    CustomerEdit,
    ContractEditDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      searchCustomerList:[],
      // 客户信息表格数据
      customerList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerId: null,
        paymentType: null,
      },
      // 付款方式数据字典
      paymentTypeOptions: [],
      // 是否显示index页面
      showIndexList:true,
      editConfig: {
        id: ''
      },
      // 是否显示弹出层
      open: false,
      // 添加合同
      contractEditConfig: {
        customerId: '',
        paymentType: ''
      },
      columns: []
    };
  },
  created() {
    this.loadColumns();
    this.getCustomerList();
    this.getList();
    this.getDicts("bus_payment_type").then(response => {
      this.paymentTypeOptions = response.data;
    });
  },
  methods: {
    // 菜单状态字典翻译
    paymentTypeFormat(row, column) {
      return this.selectDictLabel(this.paymentTypeOptions, row.paymentType);
    },
    numberFormat(row, column, cellValue, index){
        return cellValue.toLocaleString();
    },
    // 查询客户信息列表
    getCustomerList() {
      let queryParams= {
        pageNum: 1,
        pageSize: 999,
        customerName: null,
        paymentType: null,
      }

      listCustomer(queryParams).then(response => {
        this.searchCustomerList = response.rows;
      });
    },
    /** 查询客户信息列表 */
    getList() {
      this.loading = true;
      listCustomerDetail(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.customerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.editConfig.id = ''
      this.showIndexList = false
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.editConfig.id = row.customerId
      this.showIndexList = false
    },
    /** 添加合同按钮操作 */
    handleAddContract(row) {
      this.contractEditConfig = {
        customerId: row.customerId,
        paymentType: row.paymentType
      }

      this.open = true;
      //this.title = "添加合同";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const customerIds = row.customerId || this.ids;
      this.$confirm('是否确认删除客户名称为"' + row.customerName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCustomer(customerIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有客户信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCustomer(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    editBack(val) {
      this.showIndexList = true
      this.getList()
    },
    contractEditBack(val){
      this.open = false;
      this.getList()
    },
    handleContractClose(done){
      this.$refs["contractForm"].reset();
      this.contractEditConfig = {}
      done();
    },
    getDefaultColumns(){
      let columns = [
        { key: 0, label: `付款方式`, visible: false },
        { key: 1, label: `合同金额`, visible: true },
        { key: 2, label: `已开票金额`, visible: true },
        { key: 3, label: `未开票金额`, visible: true },
        { key: 4, label: `已开票比例%`, visible: true },
        { key: 5, label: `已收货款`, visible: true },
        { key: 6, label: `已收款比例%`, visible: true },
        { key: 7, label: `应收/预收款`, visible: true },
        { key: 8, label: `所欠货款`, visible: true },
      ];
      return columns;
    },
    loadColumns(){
      let customerColumns = window.localStorage.getItem("customer-columns")
      let columns = this.getDefaultColumns()
      if (customerColumns != null){
          columns = JSON.parse(customerColumns)
      }
      this.columns = columns;
    }
  },
  watch: {
    open: {
      handler: function(val) {
        if (!val) {
          this.getList()
        }
      }
    },
    columns:{
      handler(value){
        let str = JSON.stringify(value);
        window.localStorage.setItem("customer-columns",str)
      },
      deep: true
    }
  }
};
</script>
